package com.example.demoofimagedownloadapp.view;


import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Typeface;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.example.demoofimagedownloadapp.R;
import com.example.demoofimagedownloadapp.bean.DataBean;
import com.example.demoofimagedownloadapp.bean.ImageStoreBean;
import com.example.demoofimagedownloadapp.contract.MusicWindowContract;
import com.example.demoofimagedownloadapp.presenter.MusicWindowPresenter;
import com.youth.banner.Banner;
import com.youth.banner.indicator.CircleIndicator;
import com.youth.banner.listener.OnBannerListener;
import com.youth.banner.listener.OnPageChangeListener;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;


/**
 * @author ts
 */
public class MusicWindowActivity extends BaseActivity implements View.OnClickListener, MusicWindowContract.View, SeekBar.OnSeekBarChangeListener {
    private static final String TAG = MusicWindowActivity.class.getName();
    private MusicWindowPresenter mPresenter;
    private boolean passChangeFlag = false;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.music_layout);
        Log.d(TAG, "onCreate: DONE");

        try {
            mPresenter = new MusicWindowPresenter(this);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        mPresenter.setView(this);

        if (ContextCompat.checkSelfPermission(MusicWindowActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(MusicWindowActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
        } else {
            mPresenter.initMediaPlayer();//初始化播放器 MediaPlayer
        }
        initView();
    }

    Button btPlay;
    SeekBar seekProgress;
    TextView textTitle;
    Banner banner;
    private void initView () {
        Log.d(TAG, "initView: DONE");
        Button bt_gotoMain = findViewById(R.id.bt_goto_main);
        bt_gotoMain.setOnClickListener(this);

        btPlay = findViewById(R.id.bt_play);
        Button btPrevious = findViewById(R.id.bt_previous);
        Button btNext = findViewById(R.id.bt_next);

        Typeface typeface = Typeface.createFromAsset(getAssets(),"fonts/iconfont.ttf");

        btPlay.setTypeface(typeface);
        btNext.setTypeface(typeface);
        btPrevious.setTypeface(typeface);

        btPlay.setOnClickListener(this);
        btNext.setOnClickListener(this);
        btPrevious.setOnClickListener(this);

        seekProgress = findViewById(R.id.seek_duration);
        seekProgress.setOnSeekBarChangeListener(this);

        textTitle = findViewById(R.id.text_song_name);

        banner = findViewById(R.id.banner);
        useBanner(banner);
    }

    private int lastValue = -1;
    public void useBanner(Banner banner) {
        Log.d(TAG, "useBanner: DONE");
        banner.setAdapter(
                mPresenter.getImageAdapter()
        ).addBannerLifecycleObserver(this)
        //添加生命周期观察者
        .setIndicator(new CircleIndicator(this))
        .setBannerGalleryEffect(240,10,0.6f)
        .setStartPosition(0)
        .setIndicatorPageChange()
        .setUserInputEnabled(false);
        banner.addOnPageChangeListener(new OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                DataBean dataBean = (DataBean)banner.getAdapter().getData(position);
                Log.d(TAG, "onPageSelected: "+position+"/"+dataBean.getSongName());
                String str = "";
                dataBean = null;
                for (int i=0;i<banner.getRealCount();i++){
                    dataBean = (DataBean)banner.getAdapter().getData(i);
                    str += i+"/"+ dataBean.getSongName() +";";
                }
                Log.d(TAG, "onPageSelected: "+str);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        Log.d(TAG, "useBanner: "+banner.getItemCount());
        banner.setOnBannerListener(new OnBannerListener() {
            @Override
            public void OnBannerClick(Object data, int position) {
                Log.d(TAG, "OnBannerClick: "+position);
            }
        });
        banner.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {


                return false;
            }
        });

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case 1:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    mPresenter.initMediaPlayer();
                } else {
                    Toast.makeText(this, "拒绝权限，将无法使用程序。", Toast.LENGTH_LONG).show();
                    finish();
                }
                break;
            default:
                break;
        }

    }
    boolean firstFlag = true;
    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.bt_goto_main:
                Intent intent = new Intent(MusicWindowActivity.this, MainActivity.class);
                startActivity(intent);
                this.finish();
                Log.d(TAG, "onClick: ");
                break;
            case R.id.bt_play:
                if (mPresenter.mPlayerFlag == false){
                    try {
                        mPresenter.startPlayer();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                } else {
                    mPresenter.pausePlayer();
                }
                break;
            case R.id.bt_next:
                try {
                    Log.d(TAG, "onClick: NEXT"+banner.getCurrentItem());
                    mPresenter.nextSong();
                    mPresenter.nextAlbumart();
                    banner.setCurrentItem(1);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                break;
            case R.id.bt_previous:
                try {
                    Log.d(TAG, "onClick: PRE"+banner.getCurrentItem());
                    mPresenter.previousSong();
                    mPresenter.previousAlbumart();
//                    banner.setCurrentItem(-1);

                    Log.d(TAG, "onClick: "+banner.getCurrentItem());

                } catch (IOException e) {
                    e.printStackTrace();
                }
                break;
            default:
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mPresenter.stop();
        mPresenter = null;
        Log.d(TAG, "onDestroy: DONE");
    }

    @Override
    public void setPresenter(MusicWindowContract.Presenter presenter) {

    }

    @Override
    public void updateMusicList() {

    }

    @Override
    public void updateMusicAlbumart(List<DataBean> list, int direction) {
        passChangeFlag = true;
        if(!list.isEmpty()){
            if(direction == 1){
                banner.setDatas(list);
            } else {
                banner.getAdapter().setDatas(list);
            }

            Log.d(TAG, "updateMusicAlbumart: "+ list);
        } else {
            Log.d(TAG, "updateMusicAlbumart: LIST EMPTY");
        }
        passChangeFlag = false;
    }

    /**
     * @view flash player status;
     * @param maxProgress
     */
    @Override
    public void updateMusicPlayer(long maxProgress, String title, Bitmap bitmap) {
        seekProgress.setMax((int) maxProgress);
        if(mPresenter.mPlayerFlag == true) {
            btPlay.setText(R.string.icon_pause);
        } else {
            btPlay.setText(R.string.icon_play_on);
        }
        if (title!=null){
            textTitle.setText(title);
        }

    }

    @Override
    public void updateProgress(int progress) {
        seekProgress.setProgress(progress);
        Log.d(TAG, "updateProgress: "+progress);
    }

    @Override
    public void showErrorInfo(String info) {
        Toast.makeText(this,info,Toast.LENGTH_SHORT).show();
        Log.d(TAG, "showErrorInfo: "+info);
    }

    @Override
    public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
        if(i == seekBar.getMax()){
            try {
                mPresenter.pausePlayer();
                mPresenter.nextSong();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {

    }

    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {
        if(seekBar.getProgress() != seekBar.getMax()){
            mPresenter.setProgress(seekBar.getProgress());
        }
        Log.d(TAG, "onStopTrackingTouch: "+seekBar.getProgress());
    }
}